import { createSlice } from "@reduxjs/toolkit";
import axios, { type AxiosResponse } from "axios";
import token from '@/api/token'

const counterStore = createSlice({
  name: "chat",
  // 初始化state
  initialState: {
    chatRecord: [] as any[],
    conversation_id:""
  },
  // 修改状态的方法 同步方法 支持直接修改
  reducers: {
    setChatId(state, action){
      state.conversation_id=action.payload;
    },
    setRecord(state, action) {
      console.log(action.payload, "chatRecord");
      state.chatRecord = action.payload;
    },
    pushRecord(state, action) {
      
      state.chatRecord = [...state.chatRecord, action.payload];
    },
    updateChat(state, action) {
      
      // console.log(action.payload,"state.chatRecord")
      if (state.chatRecord.length > 0) {
      state.chatRecord[state.chatRecord.length-1].content = action.payload;
      }
    },
  },
});

// 解构出来actionCreater函数
const { setRecord ,pushRecord,updateChat,setChatId} = counterStore.actions;

const fetchChatRecord = (v: any) => {
  return async (dispatch:any) => {
    const res = await axios.get(
      "http://172.16.1.118:7861/chat/knowledge_base_chat/messages",

      {
        params: {
          user_id: 356,
          conversation_id: v,
        },
        headers: {
          Authorization: `Bearer ${localStorage.getItem("react_token")}`,
        },
      }
    );
    console.log(res,"res")
    let newlist: any[]= []
    res.data.data.forEach((item: any) => {
      const list = [
        {
          conversationId: item.conversation_id || '',
          messageId: item.message_id || '',
          dateTime: '',
          error: false,
          isReply: false,
          like_or_dislike: item.like_or_dislike,
          collect_state: item.collect_state,
          additional_state: item.additional_state,
          kbName: item.name,
          content: item.query,
          showToolBar: false,
          thinking: false
        },
        {
          conversationId: item.conversation_id || '',
          messageId: item.message_id || '',
          dateTime: '',
          error: false,
          isReply: true,
          like_or_dislike: item.like_or_dislike,
          collect_state: item.collect_state,
          additional_state: item.additional_state,
          kbName: item.name === '' ? '模型能力': item.name,
          requestOptions: { prompt: item.query, options: null },
          reference: item.sources,
          content: item.response,
          showToolBar: true,
          thinking: false
        },
      ]  
      newlist = [...newlist, ...list]
       
    })
    dispatch(setRecord(newlist))
    dispatch(setChatId(v))
  };
};

// 获取reducer
const reducer = counterStore.reducer;

// 以按需导出的方式导出actionCreater
export { setRecord,pushRecord,setChatId, updateChat,fetchChatRecord };
// 以默认导出的方式导出reducer
export default reducer;
